<?php
/**
 * +----------------------------------------------------------------------
 * | 九月科技-ztuc.cn
 * +----------------------------------------------------------------------
 *                      .::::.
 *                    .::::::::.            | AUTHOR: siyu
 *                    :::::::::::           | EMAIL: ztucke@ztuc.cn
 *                 ..:::::::::::'           | DATETIME: 2020/01/31
 *             '::::::::::::'
 *                .::::::::::
 *           '::::::::::::::..
 *                ..::::::::::::.
 *              ``::::::::::::::::
 *               ::::``:::::::::'        .:::.
 *              ::::'   ':::::'       .::::::::.
 *            .::::'      ::::     .:::::::'::::.
 *           .:::'       :::::  .:::::::::' ':::::.
 *          .::'        :::::.:::::::::'      ':::::.
 *         .::'         ::::::::::::::'         ``::::.
 *     ...:::           ::::::::::::'              ``::.
 *   ```` ':.          ':::::::::'                  ::::..
 *                      '.:::::'                    ':'````..
 * +----------------------------------------------------------------------
 */
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/3/14
 * Time: 17:18
 */

namespace app\store\controller;

use app\core\InitController;
use think\facade\Cookie;
use think\facade\View;
use think\facade\Db;
use think\facade\Session;
use think\facade\Config;
use think\facade\Request;
use app\common\Common;
// 引入SMTP服务器
use sendMail\SendMail;
use app\store\validate\EmsRetrievePwd as RetrieEms;
use app\store\validate\SmsRetrievePwd as RetrieSms;
use app\store\model\Ems;
use app\store\model\Sms;
use app\store\model\System as SystemModel;
use app\store\model\User as UserModel;
use app\store\model\UserToken;
use app\store\model\Image;
use app\store\model\Signin as SigninModel;
use app\store\model\UserRule;
use think\facade\Cache;
use app\store\controller\Upload;
use app\lnadmin\model\admin\Notice;

/**
 * 用户
 * Class User
 * @package app\controller\index
 */
class User extends InitController
{
    // 个人中心首页
    public function index()
    {   
           $status = UserModel::where('id',$this->user['id'])->value('status');
           if ($status == '0') return View::fetch('error/dispatch_jump'); 
           if ($this->request->isPost()) {
            $menu  = UserRule::menuRule($this->user['group_id']); // 个人中心侧边栏 
            return json($menu); 
           }
        return View::fetch('user/index', [
            'notice' => Notice::where(['uid'=>$this->user['id'], 'status'=>1])->order('create_time desc')->count(), 
            'url' => (string) \think\facade\Request::domain(), 
            'avatar' => Image::image($this->user['id'], Upload::TYPE_USER),//会员头像
        ]);
    } 
   // 清除模板，日志缓存
    public function clearTempLog()
    {
        $path = ROOT_PATH() . 'runtime' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
                //清空文件夹函数和清空文件夹后删除空文件夹函数的处理
                function deldir($path){
                //如果是目录则继续
                  if(is_dir($path)){
                //扫描一个文件夹内的所有文件夹和文件并返回数组
                  $p = scandir($path);
                  foreach($p as $val){
                //排除目录中的.和..
                 if($val !="." && $val !=".."){
                //如果是目录则递归子目录，继续操作
                 if(is_dir($path.$val)){
                //子目录中操作删除文件夹和文件
                  deldir($path.$val.'/');
                //目录清空后删除空文件夹
                 @rmdir($path.$val.'/');
                   }else{
                //如果是文件直接删除
                  unlink($path.$val);
                           }
                         }
                      }
                   }
                }
        //调用函数，传入路径deldir($path);
        try {
            $type = $this->request->request("type");
            switch ($type) {
                case 'all':
                case 'data':
                    deldir($path);
                    array_map( 'unlink', glob( root_path().'runtime'. DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR . '*.log' ) );
                    array_map( 'unlink', glob( root_path().'runtime'. DIRECTORY_SEPARATOR . 'lnadmin' . DIRECTORY_SEPARATOR . 'temp' . DIRECTORY_SEPARATOR . '*.php' ) );
                    array_map( 'unlink', glob( root_path().'runtime'. DIRECTORY_SEPARATOR . 'store' . DIRECTORY_SEPARATOR . 'temp' . DIRECTORY_SEPARATOR . '*.php' ) );
                    Cache::clear();
                    if ($type == 'data') {
                        break;
                    }

            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('清理缓存');
    }
    // 用户登录检查
    public function login()
    {     
        if ($this->request->isPost()) {

        $param = Request::param(['name', 'pass', 'captcha']);// 获取当前请求的所有变量（经过过滤）
       
        $name = $param['name'];
        $pass = $param['pass'];
           //验证规则
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                 //是否验证码
            if(seo('useryzm')=='1'){
                //验证规则
                    $this->validate($param, ['captcha|验证码输入错误请手动点击验证码刷新后重试！'=>'require|captcha']);
            }
                    $this->validate($param, 'login');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            
        $auth = UserModel::auth($name);
           
        if (empty($auth)) return $this->error(__('Account does not exist'));//判断用户名登录
        if ($auth->status != 1) return $this->error(__('The account number is abnormal'));
        // 效验码密码
        if ($auth->password !== md5($pass . $auth->salt)) {
            // 记一次登录失败次数
            $auth->save(['loginfailure' => $auth->loginfailure + 1]);
            return $this->error(__('Login password error'));
        }
            $model = UserToken::where(['token' => $auth->token])->findOrEmpty();
        
        //记录登录IP
          if($model->expire_time <= time()){
        return $this->success(true, 0, '请验证身份',url('user/authentication?email='.base64_encode($auth->email)));
              }
        //判断连续登录和最大连续登录
        if ($auth->login_time < Common::unixtime('day')) {
            $auth->successions = $auth->login_time < Common::unixtime('day', -1) ? 1 : $auth->successions + 1;
            $auth->maxsuccessions = max($auth->successions, $auth->maxsuccessions); // 更新登录时间
        $auth->save(['loginip' => $this->request->ip(), 'prev_time'=>$auth->login_time, 'login_time'=>time(), 'login_num' => $auth['login_num'] + 1]);
            } elseif ($auth->login_time > Common::unixtime('day')) {// 更新登录时间
        $auth->save(['loginip' => $this->request->ip(), 'prev_time'=>$auth->login_time, 'login_time'=>time(), 'login_num' => $auth['login_num'] + 1]);
         }
           // 保存状态
                $keep = [
                    'user_id' => $auth->id,
                    'username' => $auth->name,
                ];
            session::set('user_auth', $keep);
            // 设置token
            Session::set('userToken', $auth->token); 
        add_user_log('login', '登录网站');
        return $this->success('', 0, __('Verification successful, logging in'), url('user/index'));
        
       }
        return View::fetch('LoginRegister');
    }

    // 退出登录
    public function logout()
    {
        $user_id = $this->user['id'];
        UserToken::del($user_id); 
        add_user_log('logout');
        return $this->success(true, 0, __('Exit successful'),url('user/login'));  
    }
    /**
     * 个人中心
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: MK
     * @Time: 2020/4/12 17:29
     */
      // 默认首页
    public function home()
    {
     $list = SigninModel::order('create_time desc')->paginate(10);
        // 获取用户信息
     
        if (!empty($list)) {
            $day=[
                'msg'=>'操作成功',
                'signNum'=>SigninModel::whereTime('create_time', 'today')->where(['status' => 1])->count(),
                'code'=>200,
                'allNum' => UserModel::inlineIp()
            ];
            foreach ($list as $k => $v) {
                if ($v['user_id']){
                    $day['signList'][]=[
                        'number'=>$v['user_id'],
                        'avatar'=>Image::image($v['user_id'], Upload::TYPE_USER),//会员头像
                        'name'=>UserModel::findUser($v['user_id'])['username']??'已删除',
                        'time'=>$v['create_time'],
                        'types'=>$v['types']=='normal' ? '签到' : '补签' 
                    ];
                }
            }
            $datajson_day=json_encode($day);
        }
             //日统计
             foreach( $this->get_week() as $v) {  
                $week['data'][]=[     
                    'msg'=>'操作成功',
                    'code'=>200,
                    'date'=>$v,
                    'signNum'=>SigninModel::whereDay('create_time', $v)->where(['status' => 1])->count()??0,
                    'unSignNum'=>UserModel::inlineIp()-(SigninModel::whereDay('create_time', $v)->where(['status' => 1])->count())??0,
                ];

            }
            $datajson_week=json_encode($week);
            //周统计
             foreach( self::get_day() as $v)     {
                $month['data'][]=[    
                    'msg'=>'操作成功',
                    'code'=>200,
                    'date'=>$v,
                    'signNum'=>SigninModel::whereDay('create_time', $v)->where(['status' => 1])->count()??0,
                    'unSignNum'=>UserModel::inlineIp()-(SigninModel::whereDay('create_time', $v)->where(['status' => 1])->count())??0,
                ];

            }
            $datajson_month=json_encode($month);
              //月统计
        View::assign([
            'datajson_day'  => $datajson_day,
            'datajson_week' => $datajson_week,
            'datajson_month'=> $datajson_month,
            'sign' => SigninModel::where('user_id', $this->user['id'])
            ->whereTime('create_time', 'today')->where(['status' => 1])->count(),
            'signin' => SigninModel::whereTime('create_time', 'today')
            ->comment('查询今天签到人数')->where(['status' => 1])->count(),
            'count' => UserModel::where(['status' => 1])->comment('查询应签到人数')->count(),
            'userInfo'   => UserModel::with('userToken')->where(['id' => $this->user->id])->find(),
        ]);
        return View::fetch('home');
    }
       // 后台登录跳转等待时间界面
    public function authentication()
    {
        if ($this->request->isPost()) {
        $email = $this->request->post('email');

        $list = SystemModel::where('key','config_sina_mail')->value('jdata');
        $data = Ems::where(['email' => $email])->whereTime('create_time', 'today')
            ->group('email')->field(['email', 'MAX(times) AS times'])->findOrEmpty();

        if ($data->times >= 10) return $this->error(__('please try again tomorrow!'));

        $exptime = time() + 60 * 10;//过期时间为十分钟

        $code = rand_number();//生成6位纯数字随机验证码
        
        $subject = __('Authentication');// 邮件标题
        $sendData = SendMail::sendEmail($email,$list,$code,$subject);
        if($sendData){
        $newData = [
            'event' => __('Member authentication'),
            'times' => $data->times + 1,
            'email' => $email,
            'code' => $code,
            'exptime' => $exptime,
            'ip' => $this->request->ip(),
        ];
        Ems::create($newData);
        return $this->success(true, 0, "$sendData", 1);
        
        }else{
            
       return $this->error("$sendData");
        }
        }
        return View::fetch('user/authentication');
    }
//每周时间
    function get_week($time = '', $format='Y-m-d'){
        $weekday = date($format, strtotime('this week'));
        $date = [];
        for ($i=0; $i<7; $i++){
            $date[$i]=date($format,strtotime($weekday)+$i*86400);
        }
        return $date;

    }
    //每月时间
    public static function get_day($time = '', $format='Y-m-d'){
        $time = $time != '' ? $time : time();
        $days = date('t', $time);
        $sday = strtotime(date('Y-m-01'));
        $date = [];
        for ($i=0; $i<date('d'); $i++){
            $date[$i] = date($format ,$sday+$i*86400);
        }
        return $date;
    }
    // 身份验证
    public function authenticationCheck()
    {
        if ($this->request->isPost()) {
        $param = $this->request->param();
       if(strlen($param['code']) != 6) return $this->error('证码长度不正确');//字母全部转换成小写
        $model = Ems::where(['email' => $param['email'], 'code' => $param['code']])->find();
        if(!$model) return $this->error(__('Verification code error'));
        if ($model['exptime'] < time()) return $this->error(__('The verification code has expired'));
                 //验证码
                try{
                    $this->validate($param, ['captcha|验证码输入错误请手动点击刷新后重试！'=>'require|captcha']);
                }catch (\Exception $e){
                    $this->error($e->getMessage());
            }
        $auth = UserModel::where(['email' => $param['email']])->find();
        
        
        if ($auth->status <> 1) return $this->error(__('The account number is abnormal'));
        //判断连续登录和最大连续登录
        if ($auth->login_time < Common::unixtime('day')) {
            $auth->successions = $auth->login_time < Common::unixtime('day', -1) ? 1 : $auth->successions + 1;
            $auth->maxsuccessions = max($auth->successions, $auth->maxsuccessions);
                  // 更新登录时间
        $auth->save(['loginip' => $this->request->ip(), 'prev_time'=>$auth->login_time, 'login_time'=>time(), 'login_num' => $auth['login_num'] + 1]);
        } elseif ($auth->login_time > Common::unixtime('day')) {
                  // 更新登录时间
        $auth->save(['loginip' => $this->request->ip(), 'prev_time'=>$auth->login_time, 'login_time'=>time(), 'login_num' => $auth['login_num'] + 1]);
        }
        // 保持会话
        $map = ['user_id' => $auth->id, 'token' => $auth->token, 'expire_time' => time()+60*60*24*7, 'verification_time'=>time()];   // 30天 
            
           $list = UserToken::where(['user_id' => $auth->id])->findOrEmpty();
         if($list['user_id'] == $auth->id){
            $list->save(['expire_time' => time()+60*60*24*7, 'verification_time'=>time()]);
            }else{  // 保持会话
        $map = ['user_id' => $auth->id, 'token' => $auth->token, 'expire_time' => time()+60*60*24*7, 'verification_time'=>time()];   // 30天 
            UserToken::create($map);
            }
           // 保存状态
                $keep = [
                    'user_id' => $auth->id,
                    'username' => $auth->username,
                ];
            session::set('user_auth', $keep);
            // 设置token
            Session::set('userToken', $auth->token);
        add_user_log('authenticationCheck', '用户身份');
        return $this->success('', 0, __('Verification successful, logging in'), url('user/index'));
      }
    } 

    // 注册
    /**
     * 个人中心
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: MK
     * @Time: 2020/4/15 22:34
     */
    public function register()
    {  add_user_log('view', '注册页');
        if ($this->request->isPost()) {
            $param = $this->request->param();
                 //验证规则
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                    $this->validate($param, ['captcha|验证码'=>'captcha']);
                    $this->validate($param, 'register');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }    
            $param['openid'] = base64_decode($param['openid']);
            $param['nickname'] = $param['username'];
            $param['token'] = Common::token();
            $param['salt'] = Common::pwdMd5($param['password'])['salt'];
            $param['password'] = Common::pwdMd5($param['password'])['password'];
            $res = UserModel::create($param); 
        add_user_log('register', '新用户');//行为日志
         return $res ? $this->success('', 0, __('Congratulations on successful registration')) : $this->error(__('Registration failed'));

    } 
      return View::fetch('register');
    }
    // 编辑
    /**
     * 个人中心
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: MK
     * @Time: 2020/4/15 22:34
     */
    public function profile()
    {  
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $verify = input('_verify', true);
            
                 //验证规则
            if($verify!='0'){
                try{
                    $this->validate($param, 'profile');
                }catch (\Exception $e){
                   $this->error($e->getMessage());
                }
            }    
           $edit = UserModel::profile($param);
            add_user_log('profile', '编辑会员资料');//行为日志
        return $edit ? $this->saveSuccess() : $this->error();
          }
          $phoneNumber = UserModel::findUser($this->user['id']);
          $maskedNumber = substr($phoneNumber->mobile, 0, 3). '****'. substr($phoneNumber->mobile, 7);
          $server = substr(explode('@',$phoneNumber->email)[0], 0, -4) . '****@' . explode('@',$phoneNumber->email)[1];
        return View::fetch('/user/profile', [
            'maskedNumber'=>$maskedNumber, 
            'users'=>$phoneNumber, 
            'server'=>$server
        ]);
    }
   
      // 修改密码
    public function change()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            // 验证条件
            $verify = input('_verify', true);
            if($verify!=''){
                try{
                    $this->validate($param, 'changePwd');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
        $model = UserModel::where(['id' => $this->user['id']])->find();

        if (!$model) return $this->error(__('ID does not exist'));
        
        $oldpass = md5($param['password'] . $model->salt);
        if ($oldpass !== $model->password) return $this->error(__('The original password is wrong'));
        $data = [
            'salt' => Common::pwdMd5($param['new_password'])['salt'],
            'password' => Common::pwdMd5($param['new_password'])['password'],
        ];
        $res = UserModel::update($data, ['id' => $this->user['id']]);
        if (!$res) return false;
            Session::delete('userToken');
            cookie('userToken',null);
        add_user_log('change', '修改会员密码');//行为日志
        return $res ? $this->success('', 0, __('Modified successfully'), url('user/login')) : $this->error(__('Modification failed'));
            }
        return View::fetch('/user/changepwd');
    }
    /**
     * 修改个人信息
     * @return array
     * @author: MK
     * @Time: 2020/4/16 20:52
     */
    
    //邮箱找回密码
    public function emailPwd()
    {
        if ($this->request->ispost()) {
        $param = Request::param(['uid', 'email']);
        if (empty($param['email'])) return $this->error(__('Email cannot be empty'));
        $pattern = '/^[a-z0-9]+([._-][a-z0-9]+)*@([0-9a-z]+\.[a-z]{2,14}(\.[a-z]{2})?)$/i';
        if (!preg_match($pattern,$param['email'])) return $this->error(__('Email format is incorrect'));
      
        switch ($param['uid'])
            {
            case 2: $list = load_config('extra/config_sina_mail','extra'); break;
            case 3: $list = SystemModel::where('key','config_enterprise_email')->value('jdata'); break;
            default: $list = SystemModel::where('key','config_qq_mail')->value('jdata');
            }
        if ($list['status'] == 0) return $this->error(__('Email function has not been turned on'));
        $model = UserModel::where(['email' => $param['email']])->find();
        if (empty($model)) return $this->error(__('Email does not exist'));
        $data = Ems::where(['email' => $param['email']])->whereTime('create_time', 'today')
            ->group('email')->field(['email', 'MAX(times) AS times'])->findOrEmpty();
        if ($data->times >= 10) return $this->error(__('please try again tomorrow'));
        $exptime = time() + 60 * 10;//过期时间为十分钟
        $code = rand_number();//生成6位纯数字随机验证码
        $subject = __('Find the password');// 邮件标题
        $sendData = SendMail::sendEmail($param['email'],$list,$code,$subject);
        if($sendData == __('Sent successfully')){//插入数据
        $newData = [
            'event'   => __('Find the password'),
            'times'   => $data->times + 1,
            'email'   => $param['email'],
            'code'    => $code,
            'exptime' => $exptime,
            'ip'      => $this->request->ip(),
        ];
         Ems::create($newData);
        return ['code' => 0,'msg'=>$sendData];
        //return $this->success(true, 0, "$sendData", 1);
        }else{  
       return $this->error("$sendData");
        }
    }
         return View::fetch('Retrievepwd');
    }
    // 邮箱找回密码验证
    public function emailcheck()
    {
        $param = $this->request->param();
        $email = $param['email'];
        
        // 实例化验证器
        $validate = new RetrieEms();
        $ems = $validate->check($param);

        // 输出验证器错误信息
        if (true !== $ems) return $this->error($validate->getError());
        $code = $param['code'];//字母全部转换成小写
        
        $password = $param['password'];
        $model = Ems::where(['email' => $email, 'code' => $code])->find();
         if(strtoupper($code)<>strtoupper($model['code'])) return $this->error(__('Verification code error'));
        if ($model['exptime'] < time()) return $this->error(__('The verification code has expired'));
        
        $data = [
            'salt' => Common::pwdMd5($password)['salt'],
            'password' => Common::pwdMd5($password)['password'],
        ];
        $res = UserModel::update($data, ['email' => $email]);

        add_user_log('emailcheck', '会员密码');//行为日志
        return $res ? $this->success('', 0, __('Modified successfully'), url('user/login')) : $this->error(__('Modification failed'));
    }

    //手机找回密码
    public function smspwd()
    {
        if ($this->request->isPost()) {
        $uid = $this->request->post('uid');
        $mobile = $this->request->post()['mobile'];
        $preg_phone='/^1[3456789]\d{9}$/ims';
 
        if (!$mobile) return $this->error(__('Mobile phone cannot be empty'));
        if (!preg_match($preg_phone,$mobile)) return $this->error(__('Incorrect format of mobile phone number'));
        
        $model = UserModel::where(['mobile' => $mobile])->find();

        if (empty($model)){
           return $this->error(__('Mobile phone does not exist')); 
        } 

        $list = SystemModel::where('key','config_sms')->value('jdata')["status"];
        if ($list == 0) return $this->error(__('SMS function has not been turned on'));

        $data = Sms::where(['mobile' => $mobile])->whereTime('create_time', 'today')
            ->group('mobile')->field(['mobile', 'MAX(times) AS times'])->findOrEmpty();
        if ($data->times >= 3) return $this->error(__('please try again tomorrow'));

        $statusStr = array(
            "0"  => "短信发送成功",
            "-1" => "参数不全",
            "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
            "30" => "密码错误",
            "40" => "账号不存在",
            "41" => "余额不足",
            "42" => "帐户已过期",
            "43" => "IP地址限制",
            "50" => "内容含有敏感词"
        );
        $smsapi = $list['url'];
        $user = $list['name']; //短信平台帐号
        $pass = md5($list['key']); //短信平台密码

        $code = rand_number();//生成6位纯数字随机验证码
        $content = str_replace('{code}', $code, $list['moban']);//要发送的短信内容
        $phone = $mobile;//要发送短信的手机号码
        $sendurl = $smsapi . "sms?u=" . $user . "&p=" . $pass . "&m=" . $phone . "&c=" . urlencode($content);
        $result = file_get_contents($sendurl);
        
             if ($result == 0 ){

                $exptime = time() + 60 * 10;//过期时间为十分钟

                    // 重新组装数据
                    $newData = [
                        'event'   => __('Find the password'),
                        'times'   => $data->times + 1,
                        'mobile'  => $mobile,
                        'code'    => $code,
                        'exptime' => $exptime,
                        'ip'      => $this->request->ip(),
                    ];
                    Sms::add($newData);
                  $result = "短信发送成功";
                }elseif($result == -1) {
                  $result = "参数不全";
                } elseif ($result == -2) {
                  $result = "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！";
                }elseif($result == 30) {
                  $result = "密码错误";
                } elseif ($result == 40) {
                  $result = "账号不存在";
                } elseif ($result == 41) {
                  $result = "余额不足";
                }elseif($result == 42) {
                  $result = "帐户已过期";
                } elseif ($result == 43) {
                  $result = "IP地址限制";
                } elseif ($result == 50) {
                  $result = "内容含有敏感词";
             
           } else {
               return $this->error(__('Unknown error, failed to send'));
          }
        
        return ['code' => 0, 'msg'=>$result];
      }
    }
    // 手机找回密码验证sms
    public function mobilecheck()
    {
        $post = $this->request->post();
        $mobile = $post['mobile'];
         
        // 实例化验证器
        $validate = new RetrieSms();
        $sms = $validate->check($post);

        // 输出验证器错误信息
        if (true !== $sms) return $this->error($validate->getError());
        $code = $post['code1'];
        $password = $post['pass'];
        $model = Sms::where(['mobile' => $mobile, 'code' => $code])->find();
         if(empty($model)) return $this->error(__('Verification code error'));
         if ($model['exptime'] < time()) return $this->error(__('The verification code has expired'));
        
        
        $data = [
            'salt' => Common::pwdMd5($password)['salt'],
            'password' => Common::pwdMd5($password)['password'],
        ];
        $datas = UserModel::where(['mobile' => $mobile])->find();
        $res = UserModel::update($data, ['mobile' => $mobile]);
        return $res ? $this->success('', 0, __('Modified successfully'), url('user/login')) : $this->error('修改失败!');
    }

    //修改邮箱
    public function email()
    {
        if ($this->request->isPost()) {
        $param = Request::param(['uid', 'email', 'oldEmail']);
        $pattern = '/^[a-z0-9]+([._-][a-z0-9]+)*@([0-9a-z]+\.[a-z]{2,14}(\.[a-z]{2})?)$/i';
        if (empty($param['email'])) return $this->error(__('Email cannot be empty')); 
        if (empty(preg_match($pattern,$param['email']))) return $this->error('新' . __('Email format is incorrect'));
        if (empty(preg_match($pattern,$param['oldEmail']))) return $this->error('源' . __('The new email format is incorrect'));

        switch ($param['uid'])
            {
            case 2: $list = load_config('extra/config_sina_mail','extra'); break;
            case 3: $list = SystemModel::where('key','config_enterprise_email')->value('jdata')["status"]; break;
            default: $list = SystemModel::where('key','config_qq_email')->value('jdata')["status"];
            } 
        if ($list == 0) return $this->error(__('Email function has not been turned on'));
        $model = UserModel::where(['status' => 1])->select()->toArray(); // 判断是否存在
       
            foreach ($model as $k => $v) 
            {    
                if($v['id'] == $this->user->id && $v['email'] !== $param['oldEmail']) return $this->error(__('Original email error'));
                if ($v['email'] == $param['email']) return $this->error(__('Mailbox already exists')); 
          }
        $data = Ems::where(['email' => $param['email']])->whereTime('create_time', 'today')
            ->group('email')->field(['email', 'MAX(times) AS times'])->findOrEmpty();
        if ($data->times >= 10) return $this->error(__('please try again tomorrow'));
        $exptime = time() + 60 * 10;//过期时间为十分钟
        $code = rand_number();//生成6位纯数字随机验证码
        $subject = __('Modify mailbox');// 邮件标题
        $sendData = SendMail::sendEmail($param['email'],$list,$code,$subject);
        if($sendData == __('Sent successfully')){//插入数据
        $newData = [
            'event'   => __('Change mailbox'),
            'times'   => $data->times + 1,
            'email'   => $param['email'],
            'code'    => $code,
            'exptime' => $exptime,
            'ip'      => $this->request->ip(),
        ];
         Ems::create($newData);
        //return ['code' => 0, 'captcha' => $code,'msg'=>'发送成功'];
       return $this->success(true, 0, "$sendData", 1);
        }else{ 
       return $this->error("$sendData");
        }
    }
         return View::fetch('email');
    }
    // 修改邮箱验证
    public function changeemail()
    {
        $post  = $this->request->post();
        $id    = $post['id'];
        $username    = $post['username'];
        $email = $post['email'];
        
        $pattern = '/^[a-z0-9]+([._-][a-z0-9]+)*@([0-9a-z]+\.[a-z]{2,14}(\.[a-z]{2})?)$/i';
        if (!$email) return $this->error(__('Email cannot be empty')); 
        if (!preg_match($pattern,$email)) return $this->error(__('Email format is incorrect'));
        $code  = $post['code'];//字母全部转换成大写
         if (strlen($code) < 6 or strlen($code) > 6) return $this->error(__('Incorrect length of verification code'));
        $model = Ems::where(['email' => $email, 'code' => $code])->find();

        if(strtoupper($code)<>strtoupper($model['code'])) return $this->error(__('Verification code error'));
        
        if ($model['exptime'] < time()) return $this->error(__('The verification code has expired'));
        $res = UserModel::update(['email' => $email], ['id' => $id]); 

        return $res ? $this->success('', 0, __('Modified successfully'), 1) : $this->error(__('修改失败'));
    }

    //修改手机
    public function mobile()
    {
        if ($this->request->isPost()) {
        $uid = $this->request->post('uid');
        $oldMobile = $this->request->post()['oldMobile']; 
        $mobile = $this->request->post()['mobile'];
        $preg_phone='/^1[3456789]\d{9}$/ims';
        if (!$mobile) return $this->error(__('Mobile phone cannot be empty'));
        if (!preg_match($preg_phone,$mobile)) return $this->error(__('Incorrect format of mobile phone number'));
        $list = SystemModel::where('key','config_sms')->value('jdata');
        if ($list["status"] == 0) return $this->error(__('SMS function has not been turned on'));
         $model = UserModel::where(['status' => 1])->select();// 判断是否存在
            foreach ($model as $k => $v) 
            {   
                if($v['id'] == $this->user->id && $v['mobile'] !== $oldMobile) return $this->error('原手机号错误');
                if ($v['mobile'] == $mobile) return $this->error(__('Mobile phone already exists'));
        }
        $data = Sms::where(['mobile' => $mobile])->whereTime('create_time', 'today')
            ->group('mobile')->field(['mobile', 'MAX(times) AS times'])->findOrEmpty();
        if ($data->times >= 3) return $this->error(__('please try again tomorrow'));
        $statusStr = array(
            "0"  => "短信发送成功",
            "-1" => "参数不全",
            "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
            "30" => "密码错误",
            "40" => "账号不存在",
            "41" => "余额不足",
            "42" => "帐户已过期",
            "43" => "IP地址限制",
            "50" => "内容含有敏感词"
        );
        $smsapi = $list['url'];
        $user = $list['name']; //短信平台帐号
        $pass = md5($list['key']); //短信平台密码

        $code = rand_number();//生成6位纯数字随机验证码
        $content = str_replace('{code}', $code, $list['moban']);//要发送的短信内容
        $phone = $mobile;//要发送短信的手机号码
        $sendurl = $smsapi . "sms?u=" . $user . "&p=" . $pass . "&m=" . $phone . "&c=" . urlencode($content);
        $result = file_get_contents($sendurl);
         if ($result == 0 ){

                $exptime = time() + 60 * 10;//过期时间为十分钟

                    // 重新组装数据
                    $newData = [
                        'event'   => __('Modify phone'),
                        'times'   => $data->times + 1,
                        'mobile'  => $mobile,
                        'code'    => $code,
                        'exptime' => $exptime,
                        'ip'      => $this->request->ip(),
                    ];
                    Sms::add($newData);
                  $result = "短信发送成功";
                }elseif($result == -1) {
                  $result = "参数不全";
                } elseif ($result == -2) {
                  $result = "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！";
                }elseif($result == 30) {
                  $result = "密码错误";
                } elseif ($result == 40) {
                  $result = "账号不存在";
                } elseif ($result == 41) {
                  $result = "余额不足";
                }elseif($result == 42) {
                  $result = "帐户已过期";
                } elseif ($result == 43) {
                  $result = "IP地址限制";
                } elseif ($result == 50) {
                  $result = "内容含有敏感词";
             
           } else {
               return $this->error(__('Unknown error, failed to send'));
          }
        
        return ['code' => 0, 'msg'=>$result];
       }
           return View::fetch('mobile');
    }

    // 修改手机验证
    public function changemobile()
    {
        $post   = $this->request->post();
        $mobile = $post['mobile'];
        $preg_phone='/^1[3456789]\d{9}$/ims';
        if (!$mobile) return $this->error(__('Mobile phone cannot be empty'));
        if (!preg_match($preg_phone,$mobile)) return $this->error(__('Incorrect format of mobile phone number'));
        $code   = $post['code'];
          if (!$code) return $this->error(__('Verification code cannot be empty'));
          if (strlen($code) < 6 or strlen($code) > 6) return $this->error(__('Incorrect length of verification code'));
        $id     = $this->user['id'];
        $model  = Sms::where(['mobile' => $mobile, 'code' => $code])->find();
        $newtime = time();
        if ($model['code'] !== $code) return $this->error(__('Verification code error'));
        if ($model['exptime'] < $newtime) return $this->error(__('The verification code has expired'));
        $res = UserModel::update(['mobile' => $mobile], ['id' => $id]);
        return $res ? $this->success('', 0, __('Modified successfully'), 1) : $this->error(__('Modification failed'));
    }
}